let mongoose = require('mongoose');

let names = [];         // 游戏名
let links = [];         // 链接对象组
let friendLinkArr = []; // 版本链接

let getFriendlyLinkData = async function(nameArr){
    let FriendlyLinkModel = mongoose.models['FriendlyLink'];
    let newArr = nameArr.filter(item => {
        return !names.includes(item);
    });
    if(!newArr.length) return;
    let data = await FriendlyLinkModel.find({name: {$in: newArr}});
    links = links.concat(data);
    names = names.concat(newArr);
};

let getFriendlyLink = async function(){
    names = [];
    links = [];
    friendLinkArr = [];
    let time = Date.now();
    try{
        // let FriendlyLinkModel = mongoose.models['FriendlyLink'];
        let FriendlyLinkGroupModel = mongoose.models['FriendlyLinkGroup'];
        let oneMonthTime = 30 * 24 * 60 * 60 * 1000;    // 查找一个月的友情链接组
        let groups = await FriendlyLinkGroupModel.find({timeTick: {$gt: (Date.now() - oneMonthTime)}});
        let defaultGroups = await FriendlyLinkGroupModel.find({timeTick: 0});
        if(defaultGroups.length){
            groups = groups.concat(defaultGroups);
        }
        // console.log('groups==', groups);
        groups.sort((a, b) => {
            return a.timeTick - b.timeTick;
        });
        for(let i = 0 ; i < groups.length ; i++){
            if(!groups[i].list.length){
                continue;
            }
            let version = groups[i].version;
            let obj = friendLinkArr.find(item => item.version == version);
            let flag = false;
            if(!obj){
                flag = true;
                obj = {version: version || null, list: []};
            }
            let nameArr = groups[i].list.split(',');
            await getFriendlyLinkData(nameArr);
            // let data = await FriendlyLinkModel.find({name: {$in: nameArr}});
            for(let j = 0; j < nameArr.length; j++){
                let fl = links.find(item => item.name == nameArr[j]);
                // let fl = await FriendlyLinkModel.findOne({name: nameArr[j]});
                if(!fl){
                    continue
                }
                obj.list.push({
                    imgUrl: fl.imgUrl,
                    appKey: fl.appKey,
                    appName: fl.appName,
                    sceneName: groups[i].scene,
                    path: fl.path,
                    isMovie: fl.isMovie,
                });
            }
            if(!flag){
                continue;
            }
            friendLinkArr.push(obj);
            // console.log('obj =', obj);
        }
    }catch(e){
        console.error('stack ====', e.stack);
    }
    console.log('getFriendlyLink time ==', Date.now() - time);
    // console.log('friendLinkArr =', JSON.stringify(friendLinkArr));
};

let linkTimer = function(){
    setTimeout(()=>{
        getFriendlyLink();
    }, 6 * 1000);
    setInterval(()=>{
        getFriendlyLink();
    }, 7 * 60 * 1000);
};

// linkTimer();

module.exports={
    run(){
        linkTimer();
    },
    list(options){
        try{
            console.log('options =', options.version);
            let version = options.version ? options.version : '无';
            let friendlyLinks = friendLinkArr.find( item => {return item.version == version});
            if(!friendlyLinks){
                friendlyLinks = friendLinkArr[friendLinkArr.length - 1] || {list: []};
            }
            return friendlyLinks.list;
        }catch(e){
            console.error('createList error ==>', e, e.stack);
            return [];
        }
    },
    add:async function(options){
        let FriendlyLinkModel=mongoose.models['FriendlyLink'];
        console.log(options);
        await FriendlyLinkModel.create({
            sceneName:options.sceneName,
            area:options.area,
            imgUrl:options.imgUrl,
            appId:options.appId,
            appName:options.appName,
            extraData:JSON.parse(options.extraData),
            path:options.path
        })
    },
    edit:async function(options){
        let FriendlyLinkModel=mongoose.models['FriendlyLink'];
        let friendlyLink=await FriendlyLinkModel.findOne({_id:options._id});
        if(!friendlyLink){
            throw new Error('这个友情链接不存在');
        }
        friendlyLink.sceneName=options.sceneName;
        friendlyLink.area=options.area;
        friendlyLink.imgUrl=options.imgUrl;
        friendlyLink.appId=options.appId;
        friendlyLink.appName=options.appName;
        friendlyLink.extraData=JSON.parse(options.extraData);
        friendlyLink.path=options.path;
        await friendlyLink.save();
    },
    delete:async function(options){
        let FriendlyLinkModel=mongoose.models['FriendlyLink'];
        let friendlyLink=await FriendlyLinkModel.findOne({_id:options._id});
        if(!friendlyLink){
            throw new Error('这个友情链接不存在');
        }
        await FriendlyLinkModel.deleteOne({_id:options._id});
    }
};